package com.mike.uaa.server.authentication;

import com.mike.uaa.core.Authentication;
import com.mike.uaa.core.DefaultAuthenticationToken;
import com.mike.uaa.server.authentication.provider.AuthenticationProvider;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.util.List;

/**
 * <p>
 * 认证提供管理器，通过实现{@link AuthenticationManager} 认证管理器去处理认证核心逻辑
 * 认证实现是通过委托的设计模式去设计实现的，认证方案统一由{@link AuthenticationProvider}
 * 来提供.
 * </p>
 *
 * @author z zhang
 */
@Slf4j
@Component
public class DefaultAuthenticationManager implements AuthenticationManager {

    private final List<AuthenticationProvider> authenticatorsProviders;

    public DefaultAuthenticationManager(List<AuthenticationProvider> authenticatorsProviders) {
        Assert.notNull(authenticatorsProviders, "身份验证器不能为空");
        this.authenticatorsProviders = authenticatorsProviders;
    }

    @Override
    public Authentication authenticate(Authentication authentication) {

        for (AuthenticationProvider authenticationProvider : this.authenticatorsProviders) {
            if (authenticationProvider.supports(authentication.getClass())) {
                //认证
                return authenticationProvider.authenticate(authentication);
            }
        }
        log.error("没有支持的身份验证器：{}", authentication.getClass());
        return DefaultAuthenticationToken.builder().build();
    }
}
